﻿@{
    ViewBag.Title = "Form";
    Layout = "~/Views/Shared/_Form.cshtml";
}
@using LeSoft.Application.Code;
<!--jqgrid表格组件start-->
<link href="~/Content/scripts/plugins/jqgrid/jqgrid.css" rel="stylesheet" />
<script src="~/Content/scripts/plugins/jqgrid/grid.locale-cn.js"></script>
<script src="~/Content/scripts/plugins/jqgrid/jqgrid.min.js"></script>
<!--表格组件end-->
<script>
    var keyValue = request('keyValue');
    var _BillType = request('BillType');
    var _TypeId = request('Type');
    var _enCode = "", _TypeName = "";
    var _State = "0";
    var _organizeId = "@OperatorProvider.Provider.Current().CompanyId";
    $(function () {
        //单据自动编码
        if ('@ViewBag.ShopMode' == "True") {
            Code = '@ViewBag.GCode'
            checkBillCode('Code', '@ViewBag.GCode');
        }
        initControl();
    })
    //初始化控件
    function initControl() {
        var Mode = "@ViewBag.Mode";
        if (Mode == "True") {
            $("#Code").attr("placeholder", "系统已启用自动编号").attr("disabled", "disabled");
        } else {
            $("#Code").attr("isvalid", "yes").attr("checkexpession", "NotNull").attr("placeholder", "请输入编号");
        }
        $("#SendBtn").attr("disabled", "disabled");
        if (_BillType == "1") {
            _enCode = "OpenShopWorkType";
        }
        else if (_BillType == "2") {
            _enCode = "CloseShopWorkType";
        }
        else {
            _enCode = "";
        }
        //组织机构
        $("#Organize").ComboBoxTree({
            url: "../../BaseManage/Organize/GetTreeJsonById",
            description: "==请选择==",
            height: "200px",
            click: function (item) {
                _organizeId = item.id;
                if (_TypeId != "" && _State == 0) {
                    $('#gridTable').GridUnload(); GetGrid();
                }
            }
        });
        if (_organizeId != "") $("#Organize").ComboBoxSetValue(_organizeId);

        //类别
        $("#Type").ComboBoxTree({
            url: "../../SystemManage/DataItemDetail/GetDataItemTreeJson",
            param: { EnCode: _enCode },
            description: "==请选择==",
            height: "200px",
            click: function (item) {
                _TypeId = item.id;
                _TypeName = item.text;
                if (_organizeId != "" && _State == 0) {
                    $('#gridTable').GridUnload(); GetGrid();
                }
            }
        });

        if (!!keyValue) {
            $.SetForm({
                url: "../../DailyEventManage/OpenShop/GetShopBillEntity",
                param: { keyValue: keyValue },
                success: function (data) {
                    debugger;
                    $("#form1").SetWebControls(data);
                    _State = data.State;
                    $("#Organize").ComboBoxTreeSetValue(data.OrganizeId);
                    $("#Type").ComboBoxTreeSetValue(data.TypeId);
                    $("#Type").attr("disabled", "disabled");
                    _TypeName = $("#Type").attr('data-text');
                    _TypeId = data.TypeId;
                    _organizeId = data.OrganizeId;
                    if (_State < 1) {
                        $("#SendBtn").removeAttr("disabled");
                        $("#Organize").attr("disabled", "disabled");
                        $("#Date").attr("disabled", "disabled");
                    }
                    else {
                        $("#Organize").attr("disabled", "disabled");
                        $("#Date").attr("disabled", "disabled");
                        $("#SendBtn").attr("disabled", "disabled");
                        GetTask();
                    }
                    switch (data.State) {
                        case 0: $("#State").val("新创建（待派单）"); break;
                        case 1: $("#State").val("派单中（已派单）"); break;
                        case 2: $("#State").val("进行中（已接单）"); break;
                        case 3: $("#State").val("已完成"); break;
                        case 4: $("#State").val("已退单"); break;
                        case 5: $("#State").val("已取消"); break;
                        default: break;
                    }
                    $('#gridTable').GridUnload(); GetCompleteGrid();
                }
            });

        }
    }

    //加载工作内容表格
    function GetGrid() {
        var selectedRowIndex = 0;
        var queryJson = new Object();
        queryJson["OrganizeId"] = _organizeId;
        queryJson["TypeId"] = _TypeId;
        queryJson["Category"] = _BillType;
        var $gridTable = $('#gridTable');
        $gridTable.jqGrid({
            datatype: "json",
            width: 1060,
            unwritten: false,
            url: "../../DailyEventManage/OpenShop/GetShopItemPageListJson",
            postData: { queryJson: JSON.stringify(queryJson) },
            height: $(window).height() - 350,
            colModel: [
                { label: "主键", name: "Id", index: "Id", hidden: true },
                { label: "主键", name: "ItemObject", index: "ItemObject", hidden: true },
                { label: "项目编号", name: "Code", index: "Code", width: 150, align: "center" },
                { label: "项目名称", name: "Name", index: "Name", width: 100, align: "center" },
                { label: "工作类型", name: "ItemName", index: "ItemName", width: 100, align: "center" },
                { label: "责任部门", name: "FullName", index: "FullName", width: 100, align: "center" },
                { label: "工作标准", name: "Criterion", index: "Criterion", width: 150, align: "center" },
                { label: "开始时间", name: "BeginTime", index: "BeginTime", width: 150, align: "center" },
                { label: "结束时间", name: "EndTime", index: "EndTime", width: 150, align: "center" }
            ],
            rownumbers: true,
            sortname: 'Code',
            sortorder: 'desc',
            rowNum: 30,
            rowList: [30, 50, 100],
            pager: "#gridPager",
            shrinkToFit: false,
            gridview: true,
            onSelectRow: function () {
                selectedRowIndex = $("#" + this.id).getGridParam('selrow');
            },
            gridComplete: function () {
                $("#" + this.id).setSelection(selectedRowIndex, false);
            },
            subGrid: true,
            subGridRowExpanded: function (subgrid_id, row_id) {
                var _itemId = $("#gridTable").jqGrid('getRowData', row_id)['Id'];
                var subgrid_table_id = subgrid_id + "_t";
                var subhtml = "";
                subhtml += '<div><table id="' + subgrid_table_id + '"></table></table></div>';
                $("#" + subgrid_id).html(subhtml);
                $("#" + subgrid_table_id).jqGrid({
                    datatype: "json",
                    url: " ../../DailyEventManage/OpenShop/GetItemObject?ItemId=" + _itemId,
                    unwritten: false,
                    colModel: [
                       { label: "Id", name: "Id", hidden: true },
                       {
                           label: "类别", name: "ObjectTypeId", width: 120, idnex: "ObjectTypeId", align: "center", sortable: false,
                           formatter: function (cellvalue, options, rowObject) {
                               switch (cellvalue) {
                                   case 0: return "房间"; break;
                                   case 1: return "商户"; break;
                                   case 2: return "公共部位"; break;
                                   case 3: return "设备"; break;
                                   case 4: return "装修现场"; break;
                                   case 5: return "内容"; break;
                                   default: return ""; break;
                               }
                           }
                       },
                       { label: "名称", name: "ObjectName", width: 120, idnex: "ObjectName", align: "center", sortable: false },
                       {
                           label: "是否需要附件", name: "PictureFlag", width: 120, idnex: "PictureFlag", align: "center", sortable: false,
                           formatter: function (cellvalue, options, rowObject) {
                               return cellvalue == 1 ? "<i class=\"fa fa-toggle-on\"></i>" : "<i class=\"fa fa-toggle-off\"></i>";
                           },
                       },
                       { label: "ObjectId", name: "ObjectId", hidden: true },
                       { label: "ItemId", name: "ItemId", hidden: true },
                       { label: "ContentId", name: "ContentId", hidden: true }
                    ],
                    rowNum: 1000,
                    rownumbers: true,
                    shrinkToFit: false,
                    gridview: true,
                    hidegrid: false
                });
            }
        });
    }

    //编辑时候加载项目表及其完成情况
    function GetCompleteGrid() {
        debugger;
        var selectedRowIndex = 0;
        var $gridTable = $('#gridTable');
        $gridTable.jqGrid({
            url: "../../DailyEventManage/OpenShop/GetItemResult",
            postData: { BillId: keyValue },
            datatype: "json",
            height: 265,
            autowidth: true,
            colModel: [
               { label: "主键", name: "Id", index: "Id", hidden: true },
               { label: "主键", name: "ItemId", index: "ItemId", hidden: true },
               { label: "项目编号", name: "Code", index: "Code", width: 150, align: "center" },
               { label: "项目名称", name: "ItemName", index: "ItemName", width: 150, align: "center" },
               { label: "责任部门", name: "FullName", index: "FullName", width: 100, align: "center" },
               { label: "开始时间", name: "BeginTime", index: "BeginTime", width: 150, align: "center" },
               { label: "结束时间", name: "EndTime", index: "EndTime", width: 150, align: "center" },
               { label: "工作标准", name: "Criterion", index: "Criterion", width: 150, align: "center" },
               {
                   label: "完成情况", name: "CompleteState", index: "CompleteState", width: 150, align: "center",
                   formatter: function (cellvalue, options, rowObject) {
                       switch (cellvalue) {
                           case 0: return "<span class=\"label label-danger\">未完成</span>"; break;
                           case 1: return "<span class=\"label label-success\">已完成</span>"; break;
                           default: return "<span class=\"label label-danger\">未完成</span>"; break;
                       }
                   }
               }
            ],
            viewrecords: true,
            rowNum: 1000,
            sortname: 'Date',
            sortorder: 'desc',
            rownumbers: true,
            shrinkToFit: false,
            gridview: true,
            onSelectRow: function (status) {
                selectedRowIndex = $("#" + this.id).getGridParam('selrow');
            },
            gridComplete: function () {
                $("#" + this.id).setSelection(selectedRowIndex, false);
            },
            subGrid: true,
            subGridRowExpanded: function (subgrid_id, row_id) {
                var ItemId = $("#gridTable").jqGrid('getRowData', row_id)['ItemId'];
                var subgrid_table_id = subgrid_id + "_t";
                var subhtml = "";
                subhtml += '<div><table id="' + subgrid_table_id + '"></table></table></div>';
                $("#" + subgrid_id).html(subhtml);
                $("#" + subgrid_table_id).jqGrid({
                    url: "../../DailyEventManage/OpenShop/GetObjectResult?BillId=" + keyValue + "&ItemId=" + ItemId,
                    datatype: "json",
                    height: 150,
                    autowidth: true,
                    colModel: [
                       { label: "主键", name: "Id", index: "Id", hidden: true },
                       { label: "名称", name: "ObjectName", index: "ObjectName", width: 150, align: "center" },
                       {
                           label: "类型", name: "ObjectTypeId", index: "ObjectTypeId", width: 150, align: "center",
                           formatter: function (cellvalue, options, rowObject) {
                               switch (cellvalue) {
                                   case 0: return "房间"; break;
                                   case 1: return "商户"; break;
                                   case 2: return "公共部位"; break;
                                   case 3: return "设备"; break;
                                   case 4: return "装修现场"; break;
                                   case 5: return "内容"; break;
                                   default: return "房间"; break;
                               }
                           }
                       },
                       {
                           label: "是否需要附件", name: "PictureFlag", width: 120, idnex: "PictureFlag", align: "center", sortable: false,
                           formatter: function (cellvalue, options, rowObject) {
                               return cellvalue == 1 ? "<i class=\"fa fa-toggle-on\"></i>" : "<i class=\"fa fa-toggle-off\"></i>";
                           },
                       },
                       {
                           label: "完成状态", name: "CompleteState", index: "CompleteState", width: 150, align: "center",
                           formatter: function (cellvalue, options, rowObject) {
                               switch (cellvalue) {
                                   case 0: return "<span class=\"label label-danger\">未完成</span>"; break;
                                   case 1: return "<span class=\"label label-success\">已完成</span>"; break;
                                   case 2: return "<span class=\"label label-danger\">已取消</span>"; break;
                                   default: return "<span class=\"label label-danger\">未完成</span>"; break;
                               }
                           }
                       },
                       { label: "完成人", name: "CompleteMan", index: "CompleteMan", width: 100, align: "center" },
                       { label: "完成时间", name: "CompleteDate", index: "CompleteDate", width: 100, align: "center" },
                    ],
                    rowNum: "all",
                    caption: "详情",
                    hidegrid: false,
                    shrinkToFit: false,
                    gridview: true
                });
            }

        });
    }

    //显示派单信息
    function GetTask() {
        $("#SendTable").removeAttr("hidden");
        $.SetForm({
            url: "../../DailyEventManage/OpenShop/GetTask",
            param: { SourceId: keyValue },
            success: function (data) {
                $("#form1").SetWebControls(data);
                var _send = data.TaskContent.split("要求：")[1];
                $("#Send").val(_send);

                if (data.ReceiveMemo != null) {
                    var _ReceiveMemo = eval("[" + data.ReceiveMemo + "]");
                    var Value = "";
                    $.each(_ReceiveMemo, function (index, item) {
                        Value += item.FromOperateName + "于" + item.Date + "时" + item.Content + ";"
                    });
                    $("#ReceiveMemo").val(Value);
                }
                if (data.ExecMemo != null) {
                    var _ExecMemo = eval("[" + data.ExecMemo + "]");
                    var Value = ""; var Date;
                    $.each(_ExecMemo, function (index, item) {
                        Value += item.UserName + "  ";
                        Date = item.Date;
                    });
                    $("#ExecMan").val(Value);
                    $("#ExecDate").val(Date);
                }

            }
        });
    }



    function btn_Send() {
        if (_TypeId == "") {
            dialogMsg("请先选择工作类型。", -1);
            return;
        }
        dialogOpen({
            id: "Form1",
            title: '派单',
            url: '/DailyEventManage/OpenShop/SendForm?TypeId=' + _TypeId,
            width: "450px",
            height: "350px",
            callBack: function (iframeId) {
                top.frames[iframeId].AcceptClick();
            }
        });
    }

    //操作记录
    function getOperateGrid() {
        $gridTable = $("#gridTable_Operate");
        $gridTable.jqGrid({
            url: "../../SystemManage/Setting/GetOperateRecordList",
            postData: { BillId: keyValue },
            datatype: "json",
            height: 650,
            hidegrid: false,
            caption: "操作记录",
            autowidth: true,
            colModel: [
               { label: '项目主键', name: 'Id', hidden: true },
                        { label: '业务类别', name: 'Type', width: 100, align: 'center', sortable: false },
                        { label: '操作人', name: 'FromOperateName', width: 100, align: 'center', sortable: false },
                        { label: '操作时间', name: 'Date', width: 170, align: 'center', sortable: false },
                        {
                            label: "操作内容", name: "Content", index: "Content", width: 590, align: "left", sortable: false,
                            formatter: function (cellvalue, options, rowObject) {
                                if (!!rowObject.ToOperateName)
                                    return "发起者：" + rowObject.FromOperateName + "，接受者：" + rowObject.ToOperateName + "<br/>" + cellvalue;
                                else
                                    return "发起者：" + rowObject.FromOperateName + "<br/>" + cellvalue;
                            }
                        },
            ],
            viewrecords: true,
            rownumbers: true,

        });
    }

    //保存表单
    function AcceptClick(obj) {
        if (!$('#form1').Validform()) {
            return false;
        }

        var ShopBill = $("#form1").GetWebControls(keyValue);
        ShopBill["OrganizeId"] = _organizeId;
        ShopBill["BillType"] = _BillType;
        ShopBill["TypeId"] = _TypeId;
        ShopBill["Type"] = $("#Type").attr('data-text');
        ShopBill["State"] = _State;

        var ShopBillDetail = [];
        var gridData = $("#gridTable").jqGrid("getRowData");
        var sort = 1;
        $.each(gridData, function (index, model) {
            $.ajax({
                url: "/DailyEventManage/OpenShop/GetItemObject?ItemId=" + model.Id,
                type: "GET",
                dataType: "json",
                async: false,
                success: function (data) {
                    if (data.length > 0) {
                        $.each(data, function (index, object) {
                            var item = {};
                            item["ItemId"] = model.Id;
                            item["SIOCId"] = object.Id;
                            if (!!keyValue) item["BillId"] = keyValue;
                            item["SortCode"] = sort;
                            ShopBillDetail.push(item);
                            sort++;
                        });
                    }
                    else {
                        var item = {};
                        item["ItemId"] = model.Id;
                        if (!!keyValue) item["BillId"] = keyValue;
                        item["SortCode"] = sort;
                        ShopBillDetail.push(item);
                        sort++;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    dialogMsg(errorThrown, -1);
                }
            });
        });
        //for (var i = 0; i < ShopBillDetail.length; i++) {
        //    ShopBillDetail[i]["ItemId"] = ShopBillDetail[i]["Id"];
        //    delete ShopBillDetail[i]["Code"]; delete ShopBillDetail[i]["FullName"]; delete ShopBillDetail[i]["Criterion"]; delete ShopBillDetail[i]["Name"]; delete ShopBillDetail[i]["Id"];
        //}
        if (ShopBillDetail.length < 0) {
            return false;
        }
        var Task = {}, TaskUser = [];
        var $Perform = $("#Perform option");
        if ($Perform.length > 0) {
            Task["TypeId"] = _TypeId;
            if (_BillType == 1) {
                Task["Category"] = 6;//开店
                Task["Type"] = "1";
                Task["Name"] = "开店处理任务";
                Task["ExecType"] = $("#Send").attr('title');
                Task["TaskContent"] = "开店任务，工作类型为" + _TypeName + ",要求：" + $("#Send").val();
            } else {
                Task["Category"] = 7;//闭店
                Task["ExecType"] = $("#Send").attr('title');
                Task["Type"] = "1";
                Task["Name"] = "闭店处理任务";
                Task["TaskContent"] = "闭店任务，工作类型为" + _TypeName + ",要求：" + $("#Send").val();
            }

            Task["State"] = 0;
            for (var i = 0; i < $Perform.length; i++) {
                var item = {};
                item["UserId"] = $($Perform[i]).attr("value");
                item["UserName"] = $($Perform[i]).text();
                TaskUser[i] = item;
            }
        }

        $.SaveForm({
            url: "../../DailyEventManage/OpenShop/ShopBillSaveForm?keyValue=" + keyValue,
            param: { ShopBill: JSON.stringify(ShopBill), ShopBillDetail: JSON.stringify(ShopBillDetail), Task: JSON.stringify(Task), TaskUser: JSON.stringify(TaskUser) },
            loading: "正在保存数据...",
            success: function () {
                $.currentIframe().$("#gridTable").trigger("reloadGrid");
            }
        });
    }
</script>
<div>
    <ul class="nav nav-tabs">
        <li class="active"><a href="#BaseInfo" data-toggle="tab">基础信息</a></li>
        <li><a href="#Related" data-toggle="tab">相关文档</a></li>
        <li><a href="#Business" data-toggle="tab" onclick="getOperateGrid()">业务日志</a></li>
    </ul>
    <div class="tab-content" style="padding-top: 15px;">
        <div style="margin-left: 10px; margin-top: 20px; margin-right: 30px;" id="BaseInfo" class="tab-pane active">
            <div @*style="border: 1px solid #BEBEBE; background-color: #f4f4f4;"*@>
                <table class="form">
                    <tr>
                        <th class="formTitle">所属机构<font face="宋体">*</font></th>
                        <td class="formValue">
                            <div id="Organize" type="select" class="ui-select" isvalid="yes" checkexpession="NotNull"></div>
                        </td>
                        <th class="formTitle">单据编号<font face="宋体">*</font></th>
                        <td class="formValue">
                            <input id="Code" type="text" class="form-control" />
                        </td>
                        <th class="formTitle">单据日期<font face="宋体">*</font></th>
                        <td class="formValue">
                            <input id="Date" type="text" class="form-control input-wdatepicker" value="@LeSoft.Util.Time.GetToday()" onfocus="WdatePicker({})" isvalid="yes" checkexpession="NotNull" />
                        </td>
                    </tr>
                    <tr>
                        <th class="formTitle">工作类型<font face="宋体">*</font></th>
                        <td class="formValue">
                            <div id="Type" type="select" class="ui-select" isvalid="yes" checkexpession="NotNull"></div>
                        </td>
                        <th class="formTitle">单据状态</th>
                        <td class="formValue">
                            <input id="State" readonly value="新创建（待派单）" type="text" class="form-control" />
                        </td>
                        <th class="formTitle"></th>
                        <td class="formValue"></td>
                    </tr>
                    <tr>
                        <th class="formTitle">附加说明</th>
                        <td class="formValue" colspan="5">
                            <input id="Memo" type="text" class="form-control" />
                        </td>
                    </tr>
                    <tr>
                        <td class="formTitle" colspan="5">
                            <table class="form" id="SendTable" hidden="hidden">
                                <tr>
                                    <th class="formTitle">派单人</th>
                                    <td class="formValue">
                                        <input id="CreateUserName" readonly type="text" class="form-control" />
                                    </td>
                                    <th class="formTitle">派单时间</th>
                                    <td class="formValue">
                                        <input id="CreateDate" readonly disabled="disabled" type="text" class="form-control input-wdatepicker" onfocus="WdatePicker({})" />
                                    </td>
                                    <th class="formTitle"></th>
                                </tr>
                                <tr>
                                    <th class="formTitle">计划执行人</th>
                                    <td class="formValue" colspan="3">
                                        <input id="Send" readonly type="text" class="form-control" />
                                    </td>
                                    <th class="formTitle"></th>
                                </tr>
                                <tr>
                                    <th class="formTitle">接单信息</th>
                                    <td class="formValue" colspan="3">
                                        <input id="ReceiveMemo" readonly type="text" class="form-control" />
                                    </td>
                                    <th class="formTitle"></th>
                                </tr>
                                <tr>
                                    <th class="formTitle">执行人</th>
                                    <td class="formValue">
                                        <input id="ExecMan" readonly type="text" class="form-control" />
                                    </td>
                                    <th class="formTitle">执行时间</th>
                                    <td class="formValue">
                                        <input id="ExecDate" readonly disabled="disabled" type="text" class="form-control input-wdatepicker" onfocus="WdatePicker({})" />
                                    </td>
                                    <th class="formTitle"></th>
                                </tr>
                            </table>
                        </td>
                        <td class="formValue"><input id="SendBtn" type="button" value="派单" style="width:90px;" onclick="btn_Send()" class="form-control"></td>
                    </tr>
                    <tr style=" height: 20px; border-bottom: 1px dashed #cecece;"><td colspan="6"></td></tr>
                    <tr>
                        <td colspan="6">
                            <div class="panel-Title" style="border:0px;">工作内容</div>
                            <table id="gridTable"></table>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div id="Business" class="tab-pane" style="margin-left: 10px; margin-top: 20px; margin-right: 30px;">
            <table id="gridTable_Operate"></table>
        </div>
</div>
<select multiple class="form-control" id="Perform" style="display:none;"></select>
